# -*- coding: utf-8 -*-
"""
HaaS506 RTU 系统模块
提供系统重启、时间戳缓存等功能
"""

import utime
import kv
import ujson as json

# 系统状态
_initialized = False
_last_timestamp = 0


def init():
    """初始化系统模块"""
    global _initialized

    try:
        # 标记重启次数
        _mark_reboot_times()

        # 读取上次时间戳
        _load_last_timestamp()

        _initialized = True
        print("[SYSTEM] System module initialized")
        return True

    except Exception as e:
        print("[SYSTEM] Init error: {}".format(e))
        return False


def _mark_reboot_times():
    """标记重启次数"""
    try:
        # 获取重启次数
        count_str = kv.get("reboot_count")
        if count_str:
            count = int(count_str)
        else:
            count = 0
        count += 1
        kv.set("reboot_count", str(count))

        # 获取上次时间戳
        last_timestamp = get_last_timestamp()

        print(
            "[SYSTEM] System reboot #{} times, last timestamp: {}".format(
                count, last_timestamp
            )
        )

    except Exception as e:
        print("[SYSTEM] Mark reboot times error: {}".format(e))


def restart(delay=3):
    """重启系统（保存时间戳后重启）"""
    print("[SYSTEM] Preparing to restart system...")

    # 保存当前时间戳
    save_last_timestamp()

    # 延时重启
    if delay > 0:
        print("[SYSTEM] System will restart in {} seconds...".format(delay))
        utime.sleep(delay)

    print("[SYSTEM] Rebooting system...")

    # 尝试使用原生reboot函数
    try:
        # 在HaaS506平台上，reboot是全局函数
        reboot()
    except NameError:
        # 如果没有reboot函数，尝试其他方式
        try:
            import machine

            machine.reset()
        except:
            # 最后尝试使用sys.exit
            try:
                import sys

                sys.exit()
            except:
                print("[SYSTEM] Reboot failed, no reboot method available")


def save_last_timestamp():
    """保存当前时间戳到KV存储"""
    try:
        current_time = utime.time()

        # 检查时间戳是否合理（2025年的时间戳应该大于1735689600）
        if current_time > 1735689600:  # 2025-01-01 00:00:00
            kv.set("last_timestamp", str(current_time))

            # 格式化时间保存
            time_info = {
                "timestamp": current_time,
                "formatted": _format_time(current_time),
                "save_time": current_time,
            }
            kv.set("last_time_info", json.dumps(time_info))

            print(
                "[SYSTEM] Last timestamp saved: {} ({})".format(
                    current_time, _format_time(current_time)
                )
            )
        else:
            print("[SYSTEM] Invalid timestamp, not saving: {}".format(current_time))

    except Exception as e:
        print("[SYSTEM] Save last timestamp error: {}".format(e))


def get_last_timestamp():
    """获取上次保存的时间戳"""
    try:
        timestamp_str = kv.get("last_timestamp")
        if timestamp_str:
            return int(timestamp_str)
        return 0
    except Exception as e:
        print("[SYSTEM] Get last timestamp error: {}".format(e))
        return 0


def _load_last_timestamp():
    """加载上次保存的时间戳"""
    global _last_timestamp

    try:
        _last_timestamp = get_last_timestamp()
        if _last_timestamp > 0:
            print(
                "[SYSTEM] Last timestamp loaded: {} ({})".format(
                    _last_timestamp, _format_time(_last_timestamp)
                )
            )

            # 如果当前时间不正常（比如2000年），使用缓存的时间戳
            current_time = utime.time()
            if current_time < 1609459200:  # 2021-01-01 00:00:00
                print(
                    "[SYSTEM] Current time abnormal ({}), will use cached timestamp".format(
                        current_time
                    )
                )
                return _last_timestamp

    except Exception as e:
        print("[SYSTEM] Load last timestamp error: {}".format(e))

    return 0


def get_cached_timestamp():
    """获取缓存的时间戳（用于时间同步失败时）"""
    global _last_timestamp

    # 如果有缓存的时间戳，返回它
    if _last_timestamp > 0:
        return _last_timestamp

    # 否则尝试从KV存储读取
    return get_last_timestamp()


def should_use_cached_time():
    """判断是否应该使用缓存的时间"""
    current_time = utime.time()

    # 如果当前时间早于2021年，说明时间不正常
    if current_time < 1609459200:  # 2021-01-01 00:00:00
        return True

    # 如果当前时间早于2024年，也可能是异常
    if current_time < 1704067200:  # 2024-01-01 00:00:00
        cached_time = get_cached_timestamp()
        # 如果缓存时间是2025年的，使用缓存时间
        if cached_time > 1735689600:  # 2025-01-01 00:00:00
            # 如果缓存时间大于当前时间，则使用缓存时间
            if cached_time > current_time:
                return True
            else:
                return False

    return False


def get_reboot_count():
    """获取重启次数"""
    try:
        count_str = kv.get("reboot_count")
        if count_str:
            return int(count_str)
        return 0
    except:
        return 0


def clear_reboot_count():
    """清除重启次数"""
    try:
        kv.set("reboot_count", "0")
        print("[SYSTEM] Reboot count cleared")
        return True
    except Exception as e:
        print("[SYSTEM] Clear reboot count error: {}".format(e))
        return False


def get_system_info():
    """获取系统信息"""
    try:
        import gc

        info = {
            "reboot_count": get_reboot_count(),
            "last_timestamp": get_last_timestamp(),
            "cached_timestamp": get_cached_timestamp(),
            "memory_free": gc.mem_free(),
            "memory_alloc": gc.mem_alloc(),
            "current_time": utime.time(),
            "time_normal": not should_use_cached_time(),
        }

        # 添加格式化的时间信息
        if info["last_timestamp"] > 0:
            info["last_time_formatted"] = _format_time(info["last_timestamp"])

        return info

    except Exception as e:
        print("[SYSTEM] Get system info error: {}".format(e))
        return None


def _format_time(timestamp):
    """格式化时间戳"""
    try:
        time_tuple = utime.localtime(timestamp)
        return "{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}".format(
            time_tuple[0],
            time_tuple[1],
            time_tuple[2],
            time_tuple[3],
            time_tuple[4],
            time_tuple[5],
        )
    except:
        return str(timestamp)


def save_crash_info(error_msg):
    """保存崩溃信息"""
    try:
        crash_info = {
            "error": error_msg,
            "timestamp": utime.time(),
            "formatted_time": _format_time(utime.time()),
            "reboot_count": get_reboot_count(),
        }
        kv.set("last_crash_info", json.dumps(crash_info))
        print("[SYSTEM] Crash info saved")
    except Exception as e:
        print("[SYSTEM] Save crash info error: {}".format(e))


def get_crash_info():
    """获取崩溃信息"""
    try:
        crash_str = kv.get("last_crash_info")
        if crash_str:
            return json.loads(crash_str)
        return None
    except Exception as e:
        print("[SYSTEM] Get crash info error: {}".format(e))
        return None


def test_system():
    """测试系统功能"""
    print("[SYSTEM] Testing system functionality...")

    # 显示系统信息
    info = get_system_info()
    print("[SYSTEM] System info: {}".format(info))

    # 测试时间戳保存
    save_last_timestamp()

    # 测试时间判断
    if should_use_cached_time():
        print("[SYSTEM] Should use cached time")
        cached = get_cached_timestamp()
        print("[SYSTEM] Cached timestamp: {} ({})".format(cached, _format_time(cached)))
    else:
        print("[SYSTEM] Current time is normal")

    print("[SYSTEM] System test completed")
